package com.pansoft.openplanet.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.efounder.constant.EnvironmentVariable;
import com.pansoft.openplanet.bean.CardBean;
import com.pansoft.openplanet.bean.CardWalletInfo;
import com.pansoft.openplanet.blockchain.util.StringUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

public class CardDao {

    private Context context;
    private SQLiteDatabase db;

    public CardDao(Context context) {
        this.context = context;
        db = WalletDbHelper.getInstance(context).getDb();
    }

    public void closeDb() {
        if (db != null) {
            db.close();
        }
    }

    public long insertOrReplace(CardBean cardBean) {
        ContentValues values = getContentValue(cardBean);
        return this.db.insertWithOnConflict("card", null, values,
                SQLiteDatabase.CONFLICT_REPLACE);
    }

    public long update(CardBean cardBean) {
        ContentValues values = getContentValue(cardBean);
        return this.db.update("card", values,
                "address=? and im_userid=?", new String[]{values.getAsString("address"), values.getAsString("im_userid")});
    }

    public long delete(String uid) {
        String userId = EnvironmentVariable.getProperty(CHAT_USER_ID);
        this.db.delete("card", "uid=? and user_id=?",
                new String[]{uid, userId});
        return this.db.delete("card", "uid =? and user_id=?",
                new String[]{uid, userId});
    }

    public CardBean getCardBean(String uid) {
        String userId = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String sql = "select * from card where uid=? and enable=1 and user_id = " + userId;
        List<CardBean> list = query(sql, new String[]{uid});
        return list.size() == 0 ? null : list.get(0);
    }

    public List<CardBean> getCardBeanList() {
        String userId = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String sql = "select * from card where enable=1 and user_id = " + userId;
        return query(sql, null);
    }

    private List<CardBean> query(String sql, String[] selectionArgs) {
        List<CardBean> list = new ArrayList<>();
        Cursor cursor = this.db.rawQuery(sql, selectionArgs);
        while (cursor.moveToNext()) {
            CardBean cardBean = new CardBean();
            cardBean.setEnable(cursor.getInt(cursor.getColumnIndex("enable")) == 1);
            cardBean.setUid(cursor.getString(cursor.getColumnIndex("uid")));
            String version = cursor.getString(cursor.getColumnIndex("version"));
            String cardType = cursor.getString(cursor.getColumnIndex("card_type"));
            String userId = cursor.getString(cursor.getColumnIndex("user_id"));
            String walletInfo = cursor.getString(cursor.getColumnIndex("wallet_info"));
            if (cardType == null || "".equals(cardType)) {
                cardBean.setCardType("");
            } else {
                cardBean.setCardType(cardType);
            }
            if (version == null || "".equals(version)) {
                cardBean.setVersion("");
            } else {
                cardBean.setVersion(version);
            }
            if (userId == null || "".equals(userId)) {
                cardBean.setUserId("");
            } else {
                cardBean.setUserId(userId);
            }
            if (walletInfo == null || "".equals(walletInfo)) {
                cardBean.setWalletInfoList(new ArrayList<CardWalletInfo>());
            } else {
                try {
                    List<CardWalletInfo> cardWalletInfoList = new ArrayList<>();
                    JSONArray jsonArray = new JSONArray(walletInfo);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        CardWalletInfo cardWalletInfo = new CardWalletInfo();
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        cardWalletInfo.setAddress(jsonObject.optString("address"));
                        cardWalletInfo.setChainId(jsonObject.optInt("chainId"));
                        String pos = jsonObject.optString("pos");
                        int position = 0;
                        if (!"".equals(pos)) {
                            position = Integer.valueOf(pos);
                        }
                        cardWalletInfo.setInCardPosition(Integer.valueOf(position));
                        cardWalletInfo.setWalletName(jsonObject.optString("walletName"));
                        cardWalletInfo.setWalletAvatar(jsonObject.optString("walletAvatar"));
                        cardWalletInfoList.add(cardWalletInfo);
                    }
                    cardBean.setWalletInfoList(cardWalletInfoList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            list.add(cardBean);
        }
        cursor.close();
        return list;
    }

    private ContentValues getContentValue(CardBean cardBean) {
        ContentValues values = new ContentValues();
        values.put("uid",cardBean.getUid());
        values.put("enable", cardBean.isEnable() ? 1 : 0);
        values.put("version", cardBean.getVersion() == null ? "" : cardBean.getVersion());
        values.put("card_type", cardBean.getCardType() == null ? "" : cardBean.getCardType());
        values.put("user_id", cardBean.getUserId() == null ? EnvironmentVariable.getProperty(CHAT_USER_ID) : cardBean.getUserId());
        List<CardWalletInfo> list = cardBean.getWalletInfoList();
        if (list == null) {
            values.put("wallet_info", "[]");
            return values;
        }
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> map = new HashMap<>();
            map.put("address", list.get(i).getAddress());
            map.put("chainId", list.get(i).getChainId() + "");
            map.put("pos", list.get(i).getInCardPosition() + "");
            map.put("walletName", StringUtils.isEmpty(list.get(i).getWalletName()) ?
                    "Wallet" : list.get(i).getWalletName());
            map.put("walletAvatar", list.get(i).getWalletAvatar());
            JSONObject jsonObject = new JSONObject(map);
            jsonArray.put(jsonObject);
        }
        values.put("wallet_info", jsonArray.toString());
        return values;
    }
}
